package com.yxuan.springboot.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.yxuan.springboot.mapper.EnrollmentPlanMapper;
import com.yxuan.springboot.mapper.ProfessionalScoreMapper;
import com.yxuan.springboot.mapper.SchoolInformationMapper;
import com.yxuan.springboot.mapper.SchoolScoreMapper;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.*;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.management.Query;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class SearchForSchoolServiceImpl implements SearchForSchoolService {

    @Autowired
    private OneParagraphService oneParagraphService;

    @Autowired
    private SchoolScoreService schoolScoreService;

    @Autowired
    private SchoolInformationService schoolInformationService;

    @Autowired
    private EnrollmentPlanMapper enrollmentPlanMapper;

    @Autowired
    private ProfessionalScoreMapper professionalScoreMapper;

    @Autowired
    private SchoolInformationMapper schoolInformationMapper;

    @Autowired
    private SchoolScoreMapper schoolScoreMapper;

    @Autowired
    private MongoTemplate mongoTemplate;
    //oneParagraph里会有年份，文理科，分数，意向省份四个参数
    @Override
    public List<Map<Object, Object>> selectForInfomation(OneParagraph oneParagraph) throws Exception {

        List<Map<Object, Object>> list = new ArrayList<>();
        //根据分数，意向省份，年份，文理科查询该分数对应的排名区间
        OneParagraph targetOnePara = oneParagraphService.findObjectByPramas(oneParagraph);
        //如果查询结果为null，那么直接返回不存在
        if(targetOnePara==null){

            HashMap<Object, Object> map = new HashMap<>();
            map.put("结果","没有符合条件的学校");
            list.add(map);
            return list;
        }

        //获得分数对应的位次区间
        String targetIntervals = targetOnePara.getPeopelIntervals();
        //截取位次区间字符串里最低位次的内容
        String lowest_order = targetIntervals.substring(0, targetIntervals.indexOf("-"));
        log.info("得到最低位次：" + lowest_order);
        //根据school_score表录取最低排名以及考生高考省份查询能上的所有学校school_id,即where 排名>=最低排名
        log.info("查询能上的所有学校school_id");
        List<Integer> allAvailableSchoolsId = schoolScoreService.findAllAvailableSchoolsId(lowest_order, oneParagraph.getProvince());   //这里加入分页查询，size为3

        //先每个学校逐个处理，再查每个学校里对应年份有几条选科数据，再遍历该长度，再list.add
        for (int i = 0; i < allAvailableSchoolsId.size(); i++) {                                                                        //循环分页查询的结果，对每一个结果即schoolId进行信息的查询
            HashMap<Object, Object> map = new HashMap<>();
            //对每一个学校进行信息的查询,查每个学校里对应年份有几条选科数据，再遍历该长度，再list.add
            Integer schoolId = allAvailableSchoolsId.get(i);

            //查询录取位次时条件里要带上考生省份
            SchoolInformation schoolInformation = new SchoolInformation();
            schoolInformation.setId(schoolId);

            SchoolInformation targetSchoolInfo = schoolInformationService.findObjectByPramas(schoolInformation);

            map.put("schoolName", targetSchoolInfo.getSchoolName());
            map.put("province", targetSchoolInfo.getProvince());
            map.put("regionc", targetSchoolInfo.getRegionc());
            map.put("nature", targetSchoolInfo.getNature());
            map.put("schoolType", targetSchoolInfo.getSchoolType());
            map.put("schoolCode", targetSchoolInfo.getSchoolCode());
            map.put("year", oneParagraph.getYear());


            log.info("开始plans的循环");
            List<SchoolPlans> alldatedSubjects = schoolScoreService.findAlldatedSubject(oneParagraph.getYear(), oneParagraph.getProvince(), schoolId);      //这里再传一个科目（文理科那种）
            map.put("plans", alldatedSubjects);

            log.info("plans查询完毕，进入下一环节");

            //根据schoolId查该学校有多少个专业，返回集合，遍历集合，对每个专业的数据进行统计；再统计该专业有多少个年份，进行遍历
            List<Map<Object, Object>> list1 = new ArrayList<>();
            List<String> professionalNames = enrollmentPlanMapper.findProfessionalNames(schoolId);
            int count=0;
            for (int i1 = 0; i1 < professionalNames.size(); i1++) {
                HashMap<Object, Object> professionMap = new HashMap<>();
                String professionalName = professionalNames.get(i1);

                //根据专业名称，schoolid，省份查enrollmentPlan表
                EnrollmentPlan enrollmentPlan = new EnrollmentPlan();
                enrollmentPlan.setSchoolId((long) schoolId);
                enrollmentPlan.setProfessionalName(professionalName);
                enrollmentPlan.setProvinceName(oneParagraph.getProvince());
                enrollmentPlan.setStudentYear(oneParagraph.getYear());
                enrollmentPlan.setSpecialityClassification(oneParagraph.getClassification());
                System.out.println("'sdfd','sfsf''");
                EnrollmentPlan targetEnrollmentPlan1 = enrollmentPlanMapper.queryObjectByPramas(enrollmentPlan);
                if(count==3){
                    break;
                }
                if (targetEnrollmentPlan1 == null) {
                    log.info("进入continue");
                    count++;
                    continue;
                }
                professionMap.put("professionName", professionalName);
                professionMap.put("count", targetEnrollmentPlan1.getRequirementNumber());
                professionMap.put("year", oneParagraph.getYear());
                professionMap.put("yearLength", targetEnrollmentPlan1.getSchoolLength());
                professionMap.put("tuition", targetEnrollmentPlan1.getSchoolFee());

                log.info("进入professionList环节");
                //再统计该专业有多少个年份，进行遍历
                List<Map<Object, Object>> list2 = new ArrayList<>();

                log.info("findAllYears");
                List<String> years = professionalScoreMapper.findAllYears(professionalName, schoolId, oneParagraph.getProvince(), oneParagraph.getClassification());
                for (int i2 = 0; i2 < years.size(); i2++) {
                    Map<Object, Object> map1 = new HashMap<>();
                    String targetYear = years.get(i2);
                    log.info("findTargetProfession");
                    ProfessionalScore targetProfession = professionalScoreMapper.findTargetProfession(professionalName, schoolId, oneParagraph.getProvince(), oneParagraph.getClassification(), targetYear);
                    map1.put("year", targetYear);
                    map1.put("type", oneParagraph.getClassification());
                    map1.put("lowerScore", targetProfession.getLowestScore());
                    map1.put("lowerOrder", targetProfession.getLowestOrder());
                    //根据schoolId,专业名称，科类，省份，年份求该专业所有选该科类的录取数
                    log.info(" 根据schoolId,专业名称，科类，省份，年份求该专业所有选该科类的录取数 ");
                    Integer allRequireNumbers = enrollmentPlanMapper.findAllRequireNumbers(professionalName, schoolId, oneParagraph.getProvince(), oneParagraph.getClassification(), targetYear);
                    map1.put("count", allRequireNumbers);

                    list2.add(map1);

                    if(list2.size()==3){
                        break;
                    }
                }


                professionMap.put("professionList", list2);
                //计算录取率
                log.info("计算录取率");
                log.info("list2的长度为：" + list2.size());
                double rate = 0;
                if (list2.size() != 0) {
                    Integer score = Integer.valueOf(oneParagraph.getScore());
                    Map<Object, Object> map3 = list2.get(0);
                    Object lowerScore = map3.get("lowerScore");
                    Integer schoolLowerScore = Integer.valueOf(lowerScore.toString());

                    Integer finalscore = score - schoolLowerScore;


//                if (finalscore>=10&&finalscore<20){
//                    double rate=80;
//                }else if(finalscore>0&&finalscore<10){
//                    double rate=60;
//                }else if(finalscore>&&finalscore<10) {
//
//
//
//                }
                    rate = 0;
                    if (finalscore > 20) {
                        rate = 99;
                    } else if (finalscore >= 10) {
                        rate = 80;
                    } else if (finalscore >= 0) {
                        rate = 60;
                    } else if (finalscore >= -10) {
                        rate = 20;
                    } else {
                        rate = 1;
                    }
                } else {

                    rate = 0;
                }
                professionMap.put("rate", rate);


                list1.add(professionMap);


                if(list1.size()==3){
                    break;
                }
            }
            map.put("profession", list1);
            map.put("meetRequirement", list1.size());
            double sprintable = 0;
            for (Map<Object, Object> objectObjectMap : list1) {
                sprintable += (double) objectObjectMap.get("rate");
            }
            sprintable = sprintable / list1.size();
            map.put("sprintable", sprintable);
            list.add(map);

            log.info("list长度为:"+list.size());
            if(list.size()==3){
                break;
            }


        }
        return list;
    }

    @Override
    public List<SchoolInformation> selectForInfomation1(OneParagraph oneParagraph) throws Exception {
        String classification = oneParagraph.getClassification().charAt(0) + "";
        //查oneParagraph里分数的最低位次（数字越大，位次越低）
        String Score = oneParagraph.getScore();
        String provincet = oneParagraph.getProvince();
        if(provincet.equals("广东") || provincet.equals("新疆")) {
            oneParagraph.setYear("2022");
        }else {
            oneParagraph.setYear("2023");
        }
        String rankOne = oneParagraphService.findRankOne(oneParagraph);
        String rankOneUp = null;
        String rankOneLow = null;
        if(Integer.valueOf(Score) > 480 && Integer.valueOf(Score) < 620 ){
            oneParagraph.setScore(Math.min(Integer.parseInt(Score) + 10, 749) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
//            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 45, 151) + "");
//            rankOneLow = oneParagraphService.findRankOne(oneParagraph);

            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 100, 151) + "");
            rankOneLow = oneParagraphService.findRankOne(oneParagraph);
        }else{
            oneParagraph.setScore(Math.min(Integer.parseInt(Score) + 40, 749) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
//            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 80, 151) + "");
//            rankOneLow = oneParagraphService.findRankOne(oneParagraph);

            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 150, 151) + "");
            rankOneLow = oneParagraphService.findRankOne(oneParagraph);
        }

        log.info(rankOneUp + "     " + rankOneLow);
        List<String> years = new ArrayList<>();

        if(provincet.equals("河南")){
            years.add("2022");
//            years.add("2021");

        }else{
            years.add("2022");
            years.add("2021");
            years.add("2020");
        }
        List<String> classificationList = new ArrayList<>();
        classificationList.add("综合");



//        List<ProfessionalScore> targetByParams = professionalScoreMapper.findTargetByParams(null, years, oneParagraph.getProvince(), classificationList, rankOneUp, rankOneLow);
// 获取 professionalScore 集合
        MongoCollection<Document> professional_score = mongoTemplate.getCollection("professional_score");
        // 构建查询条件
        int rankOneUpint = Integer.parseInt(rankOneUp);
        int rankOneLowint = Integer.parseInt(rankOneLow);

//        System.out.println("====================================");
//        Criteria criteria = new Criteria("lowest_order");
//        criteria.andOperator(Criteria.where("lowest_order").gt(8000).lt(50000));
//        System.out.println(criteria);


        Integer scoreInt = Integer.parseInt(Score);
        Integer pL;

        if(ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综') != null) {
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综');
        }else {
            String flog;
            if(classification.equals("物")) {
                flog = "理";
            }else {
                flog = "文";
            }
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + flog);
        }
//        log.info(pL +"++++++++++++++++++++++++++++++++++++++++++++++++++");

        if (classification.equals("物")) {
            classificationList.add("物理类");
            classificationList.add("理科");
        } else {
            classificationList.add("历史类");
            classificationList.add("文科");
        }

        String classificationJson = new Gson().toJson(classificationList);
        String province = new Gson().toJson(oneParagraph.getProvince());

        String praStr = "{\n" +
                "  $and:[\n" +
                "     {\n" +
                "       $and:[\n" +
                "         {\"lowest_order\":{$gte:"+rankOneUpint+"}},\n" +
                "         {\"lowest_order\":{$lte:"+rankOneLowint+"}},\n" +
                "         {\"province_name\":"+province+"},\n" +
                "         {\"speciality_classification\":{$in:"+classificationJson+"}},\n" +
                "         {\"enrollment_year\":{$in:"+years+"}}\n" +
                "       ]\n" +
                "     },\n" +
                " " +
                "  ]\n" +
                "}";

        boolean limtProvince = false;
        if(pL != null && scoreInt <= pL) {
            log.info("低于省控线!!!!!!!!!!!!!!!!!!!!!!!!!!");
            oneParagraph.setScore(Integer.parseInt(String.valueOf(pL)) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
            rankOneUpint = Integer.parseInt(rankOneUp);
            limtProvince = true;
            praStr = "{\n" +
                    "  $and:[\n" +
                    "     {\n" +
                    "       $and:[\n" +
                    "         {\"lowest_order\":{$gte:"+rankOneUpint+"}},\n" +
                    "         {\"province_name\":"+province+"},\n" +
                    "         {\"speciality_classification\":{$in:"+classificationJson+"}},\n" +
                    "         {\"enrollment_year\":{$in:"+years+"}}\n" +
                    "       ]\n" +
                    "     },\n" +
                    " " +
                    "  ]\n" +
                    "}";
        }
        log.info(praStr);

        //1.2根据此字符串构建查询的BSON条件
        Document query1 = Document.parse(praStr);

//        Document praDocument = Document.parse(praStr);
        //2.执行条件查询
        //2.1获取查询的文档数据
//        FindIterable<Document> documents = professional_score.find(praDocument);
        //2.2进行遍历
//        documents.iterator().forEachRemaining(temp -> System.out.println(temp));
        System.out.println("====================================");
//        query1.append("province_name", oneParagraph.getProvince());
//        query1.append("lowest_order", new Document("$gte", 50000).append("$lte", 100000));
//        query1.append("speciality_classification", new Document("$in", classificationList));
//        query1.append("enrollment_year", new Document("$in", years));

        List<Document> result2;
        // 查询数据
        if(pL != null && scoreInt <= pL) {
            Random rand = new Random();
            int min = 500;
            int max = 5000;
            int randomNumber = rand.nextInt(max - min + 1) + min;
            result2 = professional_score.find(query1).limit(5000).into(new ArrayList<>());

        }else{
            result2 = professional_score.find(query1).into(new ArrayList<>());

        }

        List<ProfessionalScore> targetByParams = result2.stream().map(this::convertToProfessionalScore).collect(Collectors.toList());

        log.info(targetByParams.toString());









        Map<String, List<ProfessionalScore>> map = new HashMap<>();
        Map<String, Integer>  sprintable = new HashMap<>();
        // 将专业装进学校当中取
        for (ProfessionalScore targetByParam : targetByParams) {
            String name = targetByParam.getSchoolName();

            if(Objects.equals(targetByParam.getProvinceName(), "内蒙古")){
                targetByParam.setRate(this.calaRate2(Integer.parseInt(targetByParam.getLowestOrder()), Integer.parseInt(rankOne)));

            }else{
                targetByParam.setRate(this.calaRate(Integer.parseInt(targetByParam.getLowestOrder()), Integer.parseInt(rankOne)));
            }
            if(limtProvince && (provincet.equals("山西") || provincet.equals("江苏"))) {
                targetByParam.setRate(0);
            }
            List<ProfessionalScore> professionalScores = map.get(name);
            if(professionalScores == null) {
                professionalScores = new ArrayList<ProfessionalScore>();
                map.put(name, professionalScores);
                sprintable.put(name, 0);
            }
            sprintable.put(name, sprintable.get(name) + targetByParam.getRate());
            professionalScores.add(targetByParam);
        }
        List<Long> schoolIdList = new ArrayList<>();
        for (String s : map.keySet()) {
            schoolIdList.add(map.get(s).get(0).getSchoolId());
        }

        List<SchoolInformation> SchoolInformation = schoolInformationMapper.querySchoolInfoById(schoolIdList);
        //
//        List<SchoolScore> scoreInfoBySchoolId = schoolScoreMapper.findScoreInfoBySchoolId(schoolIdList, oneParagraph.getProvince(), oneParagraph.getYear(), oneParagraph.getClassification());


        // 连接 MongoDB 数据库
        //MongoDatabase database = MongoClients.create("mongodb://localhost:27017").getDatabase("mydb");

// 获取 school_score 集合
        MongoCollection<Document> school_score = mongoTemplate.getCollection("school_score");

// 构建查询条件
        Document query = new Document();
//        query.append("score_year", oneParagraph.getYear());
        query.append("province", oneParagraph.getProvince());
        query.append("lot_type", oneParagraph.getClassification());
        query.append("school_id", new Document("$in", schoolIdList));
        // 查询数据
        List<Document> result = school_score.find(query).into(new ArrayList<>());
        List<SchoolScore> scoreInfoBySchoolId = result.stream().map(this::convertToSchoolScore).collect(Collectors.toList());



        //
//                                                                    education_platform.professional_score.find({
//                                                                                                                               "province_name": "provinceName",
//                                                                                                                               "lowest_order": {
//                                                                                                                           "$gte": rankOneUp,
//                                                                                                                                   "$lte": rankOneLow
//                                                                                                                       },
//                                                                                                                       "speciality_classification": {
//                                                                                                                           "$in": specialityClassification
//                                                                                                                       },
//                                                                                                                       "enrollment_year": {
//                                                                                                                           "$in": enrollmentYear
//                                                                                                                       }
//                                                                                                                       })
//

        Map<String, List<SchoolScore>> SchoolScoreMap = new HashMap<>();
        for (SchoolScore schoolScore : scoreInfoBySchoolId) {
            String schoolName = schoolScore.getSchoolName();
            List<SchoolScore> schoolScores = SchoolScoreMap.get(schoolName);
            if(schoolScores == null) {
                schoolScores = new ArrayList<>();
                SchoolScoreMap.put(schoolName, schoolScores);
            }
            schoolScores.add(schoolScore);
        }
        List<SchoolInformation> maps = new ArrayList<>();
        for (SchoolInformation schoolInformation : SchoolInformation) {
            // 排除掉外地地址
//            if(limtProvince && !schoolInformation.getProvince().equals(oneParagraph.getProvince())) {
//                // 除外城市
//                if(!oneParagraph.getProvince().equals("浙江") && !oneParagraph.getProvince().equals("海南")) {
//                    continue;
//                }
//            }
            schoolInformation.setProfessionalScore(map.get(schoolInformation.getSchoolName()));
            schoolInformation.setSprintable(sprintable.get(schoolInformation.getSchoolName()) / map.get(schoolInformation.getSchoolName()).size());
            schoolInformation.setSchoolScores(SchoolScoreMap.get(schoolInformation.getSchoolName()));
            maps.add(schoolInformation);
        }
        log.info(SchoolInformation.get(0).toString());
        return maps;
    }


    @Override
    public List<SchoolInformation> selectForInfomation2(OneParagraph oneParagraph,Integer size) throws Exception {
        String classification = oneParagraph.getClassification().charAt(0) + "";
        //查oneParagraph里分数的最低位次（数字越大，位次越低）
        String Score = oneParagraph.getScore();
        String provincet = oneParagraph.getProvince();
        if(provincet.equals("广东") || provincet.equals("新疆")) {
            oneParagraph.setYear("2022");
        }else {
            oneParagraph.setYear("2023");
        }
        String rankOne = oneParagraphService.findRankOne(oneParagraph);
        String rankOneUp = null;
        String rankOneLow = null;
        if(Integer.valueOf(Score) > 480 && Integer.valueOf(Score) < 620 ){
            oneParagraph.setScore(Math.min(Integer.parseInt(Score) + 10, 749) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 45, 151) + "");
            rankOneLow = oneParagraphService.findRankOne(oneParagraph);
        }else{
            oneParagraph.setScore(Math.min(Integer.parseInt(Score) + 40, 749) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
            oneParagraph.setScore(Math.max(Integer.parseInt(Score) - 80, 151) + "");
            rankOneLow = oneParagraphService.findRankOne(oneParagraph);
        }

        log.info(rankOneUp + "     " + rankOneLow);
        List<String> years = new ArrayList<>();

        if(provincet.equals("河南")){
            years.add("2022");
//            years.add("2021");

        }else{
            years.add("2022");
            years.add("2021");
            years.add("2020");
        }
        List<String> classificationList = new ArrayList<>();
        classificationList.add("综合");



//        List<ProfessionalScore> targetByParams = professionalScoreMapper.findTargetByParams(null, years, oneParagraph.getProvince(), classificationList, rankOneUp, rankOneLow);
// 获取 professionalScore 集合
//        MongoCollection<Document> professional_score = mongoTemplate.getCollection("professional_score");
        // 构建查询条件
        int rankOneUpint = Integer.parseInt(rankOneUp);
        int rankOneLowint = Integer.parseInt(rankOneLow);

//        System.out.println("====================================");
//        Criteria criteria = new Criteria("lowest_order");
//        criteria.andOperator(Criteria.where("lowest_order").gt(8000).lt(50000));
//        System.out.println(criteria);


        Integer scoreInt = Integer.parseInt(Score);
        Integer pL;

        if(ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综') != null) {
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综');
        }else {
            String flog;
            if(classification.equals("物")) {
                flog = "理";
            }else {
                flog = "文";
            }
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + flog);
        }
//        log.info(pL +"++++++++++++++++++++++++++++++++++++++++++++++++++");

        if (classification.equals("物")) {
            classificationList.add("物理类");
            classificationList.add("理科");
        } else {
            classificationList.add("历史类");
            classificationList.add("文科");
        }

        String classificationJson = new Gson().toJson(classificationList);
        String province = new Gson().toJson(oneParagraph.getProvince());

        String praStr = "{\n" +
                "  $and:[\n" +
                "     {\n" +
                "       $and:[\n" +
                "         {\"lowest_order\":{$gte:"+rankOneUpint+"}},\n" +
                "         {\"lowest_order\":{$lte:"+rankOneLowint+"}},\n" +
                "         {\"province_name\":"+province+"},\n" +
                "         {\"speciality_classification\":{$in:"+classificationJson+"}},\n" +
                "         {\"enrollment_year\":{$in:"+years+"}}\n" +
                "       ]\n" +
                "     },\n" +
                " " +
                "  ]\n" +
                "}";

        String praStrEs ="{\n" +
                "  \"size\": 10000,\n" +
                "  \"query\": {\n" +
                "    \"bool\": {\n" +
                "      \"must\": [\n" +

                "        {\"range\": {\"lowest_order\": {\"lt\": 109228,\"gt\": 72830}}}\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";

        System.out.println(praStrEs);
        boolean limtProvince = false;
        if(pL != null && scoreInt <= pL) {
            log.info("低于省控线!!!!!!!!!!!!!!!!!!!!!!!!!!");
            oneParagraph.setScore(Integer.parseInt(String.valueOf(pL)) + "");
            rankOneUp = oneParagraphService.findRankOne(oneParagraph);
            rankOneUpint = Integer.parseInt(rankOneUp);
            limtProvince = true;
            praStr = "{\n" +
                    "  $and:[\n" +
                    "     {\n" +
                    "       $and:[\n" +
                    "         {\"lowest_order\":{$gte:"+rankOneUpint+"}},\n" +
                    "         {\"province_name\":"+province+"},\n" +
                    "         {\"speciality_classification\":{$in:"+classificationJson+"}},\n" +
                    "         {\"enrollment_year\":{$in:"+years+"}}\n" +
                    "       ]\n" +
                    "     },\n" +
                    " " +
                    "  ]\n" +
                    "}";
        }
        log.info(praStr);

        //1.2根据此字符串构建查询的BSON条件
//        Document query1 = Document.parse(praStr);

//        Document praDocument = Document.parse(praStr);
        //2.执行条件查询
        //2.1获取查询的文档数据
//        FindIterable<Document> documents = professional_score.find(praDocument);
        //2.2进行遍历
//        documents.iterator().forEachRemaining(temp -> System.out.println(temp));
        System.out.println("====================================");
//        query1.append("province_name", oneParagraph.getProvince());
//        query1.append("lowest_order", new Document("$gte", 50000).append("$lte", 100000));
//        query1.append("speciality_classification", new Document("$in", classificationList));
//        query1.append("enrollment_year", new Document("$in", years));

        List<Document> result2;
        // 查询数据
//        if(pL != null && scoreInt <= pL) {
//            Random rand = new Random();
//            int min = 500;
//            int max = 5000;
//            int randomNumber = rand.nextInt(max - min + 1) + min;
//            result2 = professional_score.find(query1).limit(5000).into(new ArrayList<>());
//
//        }else{
//            result2 = professional_score.find(query1).into(new ArrayList<>());
//
//        }


        // es请求
        // 创建RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);






        // 发送POST请求
        String url = "http://115.231.235.17:9200/professional_score/_search";
        HttpEntity<String> requestEntity = new HttpEntity<>(praStrEs, headers);
        System.out.println(requestEntity);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        System.out.println("----------"+responseEntity);



        // 处理响应结果
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String responseBody = responseEntity.getBody();
//            System.out.println(responseBody);

            // JSON解析
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<ProfessionalScore> professionalScoreList = new ArrayList<>();
                JsonNode jsonNode = objectMapper.readTree(responseBody);

                JsonNode hitsNode = jsonNode.path("hits");
                JsonNode hitsArrayNode = hitsNode.path("hits");
                for (JsonNode hitNode : hitsArrayNode) {
                    JsonNode sourceNode = hitNode.path("_source");
//                    System.out.println(sourceNode);

                    ProfessionalScore professionalScore = objectMapper.convertValue(sourceNode,ProfessionalScore.class);
                    System.out.println(professionalScore);
                    professionalScoreList.add(professionalScore);
                }


                List<ProfessionalScore> targetByParams = professionalScoreList;
                log.info(targetByParams.toString());









                Map<String, List<ProfessionalScore>> map = new HashMap<>();
                Map<String, Integer>  sprintable = new HashMap<>();
                // 将专业装进学校当中取
                for (ProfessionalScore targetByParam : targetByParams) {
                    String name = targetByParam.getSchoolName();

                    if(Objects.equals(targetByParam.getProvinceName(), "内蒙古")){
                        targetByParam.setRate(this.calaRate2(Integer.parseInt(targetByParam.getLowestOrder()), Integer.parseInt(rankOne)));

                    }else{
                        targetByParam.setRate(this.calaRate(Integer.parseInt(targetByParam.getLowestOrder()), Integer.parseInt(rankOne)));
                    }
                    if(limtProvince && (provincet.equals("山西") || provincet.equals("江苏"))) {
                        targetByParam.setRate(0);
                    }
                    List<ProfessionalScore> professionalScores = map.get(name);
                    if(professionalScores == null) {
                        professionalScores = new ArrayList<ProfessionalScore>();
                        map.put(name, professionalScores);
                        sprintable.put(name, 0);
                    }
                    sprintable.put(name, sprintable.get(name) + targetByParam.getRate());
                    professionalScores.add(targetByParam);
                }
                List<Long> schoolIdList = new ArrayList<>();
                for (String s : map.keySet()) {
                    schoolIdList.add(map.get(s).get(0).getSchoolId());
                }

                List<SchoolInformation> SchoolInformation = schoolInformationMapper.querySchoolInfoById(schoolIdList);
                //
//        List<SchoolScore> scoreInfoBySchoolId = schoolScoreMapper.findScoreInfoBySchoolId(schoolIdList, oneParagraph.getProvince(), oneParagraph.getYear(), oneParagraph.getClassification());


                // 连接 MongoDB 数据库
                //MongoDatabase database = MongoClients.create("mongodb://localhost:27017").getDatabase("mydb");

// 获取 school_score 集合
                MongoCollection<Document> school_score = mongoTemplate.getCollection("school_score");

// 构建查询条件
                Document query3 = new Document();
//        query.append("score_year", oneParagraph.getYear());
                query3.append("province", oneParagraph.getProvince());
                query3.append("lot_type", oneParagraph.getClassification());
                query3.append("school_id", new Document("$in", schoolIdList));
                // 查询数据
                List<Document> result = school_score.find(query3).into(new ArrayList<>());
                List<SchoolScore> scoreInfoBySchoolId = result.stream().map(this::convertToSchoolScore).collect(Collectors.toList());



                //
//                                                                    education_platform.professional_score.find({
//                                                                                                                               "province_name": "provinceName",
//                                                                                                                               "lowest_order": {
//                                                                                                                           "$gte": rankOneUp,
//                                                                                                                                   "$lte": rankOneLow
//                                                                                                                       },
//                                                                                                                       "speciality_classification": {
//                                                                                                                           "$in": specialityClassification
//                                                                                                                       },
//                                                                                                                       "enrollment_year": {
//                                                                                                                           "$in": enrollmentYear
//                                                                                                                       }
//                                                                                                                       })
//

                Map<String, List<SchoolScore>> SchoolScoreMap = new HashMap<>();
                for (SchoolScore schoolScore : scoreInfoBySchoolId) {
                    String schoolName = schoolScore.getSchoolName();
                    List<SchoolScore> schoolScores = SchoolScoreMap.get(schoolName);
                    if(schoolScores == null) {
                        schoolScores = new ArrayList<>();
                        SchoolScoreMap.put(schoolName, schoolScores);
                    }
                    schoolScores.add(schoolScore);
                }
                List<SchoolInformation> maps = new ArrayList<>();
                for (SchoolInformation schoolInformation : SchoolInformation) {
                    // 排除掉外地地址
//            if(limtProvince && !schoolInformation.getProvince().equals(oneParagraph.getProvince())) {
//                // 除外城市
//                if(!oneParagraph.getProvince().equals("浙江") && !oneParagraph.getProvince().equals("海南")) {
//                    continue;
//                }
//            }
                    schoolInformation.setProfessionalScore(map.get(schoolInformation.getSchoolName()));
                    schoolInformation.setSprintable(sprintable.get(schoolInformation.getSchoolName()) / map.get(schoolInformation.getSchoolName()).size());
                    schoolInformation.setSchoolScores(SchoolScoreMap.get(schoolInformation.getSchoolName()));
                    maps.add(schoolInformation);
                }
                log.info(SchoolInformation.get(0).toString());
                return maps;



            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return null;



//        List<ProfessionalScore> targetByParams = result2.stream().map(this::convertToProfessionalScore).collect(Collectors.toList());


    }



    Integer calaRate(Integer lowerOrder, Integer myOrder) {
        Integer res = 0;
        Integer sub = lowerOrder - myOrder;
        if(sub <= 5e3) {
            res =  new Integer(Math.max((int)((25.0 / 5000) * sub + 35), 1));
        } else {
            double rate = (39. / -2.5e7) * sub  - (39. / 5e11) * sub + 255;
            res =  new Integer(Math.min((int) rate, 99));
        }
//        log.info(res.toString());
        return res;
//        if(sub >= 10000) {
//            res = 90;
//        }else if(sub >= 6000) {
//            res = 70;
//        }else if(sub >= 4500) {
//            res = 50;
//        }else if(sub >= 3000) {
//            res = 30;
//        }else if(sub >= 500){
//            res = 10;
//        }else {
//            res = 1;
//        }
//        return res;
    }

    Integer calaRate2(Integer lowerOrder, Integer myOrder) {
        Integer res = 0;
        Integer sub = lowerOrder - myOrder;
        if(sub <= 5e3) {
            res =  Math.min(new Integer(Math.max((int)((25.0 / 900) * sub + 35), 1)), 99);
        } else {
            double rate = (39. / -2.5e7) * sub  - (39. / 5e11) * sub + 255;
            res =  new Integer(Math.min((int) rate, 99));
        }
        return res;
    }

    @Override
    public Map<String, List<ProfessionalScore>> selectProfeesionByIdAndProfessionName(SchoolInformation schoolInformation) {
        System.out.println(schoolInformation.getProfessionalScore());
        List<ProfessionalScore> professionalScore = schoolInformation.getProfessionalScore();
        List<String> professionNames = new ArrayList<>();
        for (ProfessionalScore score : professionalScore) {
            professionNames.add(score.getProfessionalName());
        }
        ProfessionalScore professionalScore1 = professionalScore.get(0);
        System.out.println(professionalScore1+"+++++++++++++++++++++++");
        List<ProfessionalScore> profeesionByIdAndProfessionName = professionalScoreMapper.findProfeesionByIdAndProfessionName(professionalScore1.getProvinceName(), professionalScore1.getSchoolId(), professionNames);
        Map<String, List<ProfessionalScore>> map = new HashMap<>();
        for (ProfessionalScore score : profeesionByIdAndProfessionName.parallelStream().unordered().collect(Collectors.toList())) {
            String professionalName = score.getProfessionalName();
            List<ProfessionalScore> professionalScores = map.get(professionalName);
            if(professionalScores == null) {
                professionalScores = Collections.synchronizedList(new ArrayList<>());
                map.put(professionalName, professionalScores);
            }
            professionalScores.add(score);
        }


        log.info(profeesionByIdAndProfessionName.toString());
        return map;
    }

    @Override
    public List<SchoolScore> selectInformationBySchoolIdAndUser(Map map) throws Exception {
        String classification = (String) map.get("course_selection");
        SchoolScore schoolScore = new SchoolScore();
        schoolScore.setSchoolId((Integer) map.get("school_id"));
        schoolScore.setProvince(String.valueOf(map.get("province")));
        OneParagraph oneParagraph = new OneParagraph();
        oneParagraph.setClassification((String) map.get("course_selection"));
        oneParagraph.setScore((String) map.get("grade"));
        oneParagraph.setYear("2022");
        oneParagraph.setProvince((String) map.get("province"));
        String provincet = (String) map.get("province");
        String rankOne = oneParagraphService.findRankOne(oneParagraph);

        Integer scoreInt = Integer.parseInt(oneParagraph.getScore());
        Integer pL;

        if(ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综') != null) {
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + '综');
        }else {
            String flog;
            if(classification.equals("物")) {
                flog = "理";
            }else {
                flog = "文";
            }
            pL = ProvinceLine.provinceLineMp.get(oneParagraph.getProvince() + flog);
        }
        boolean limitProvince = false;
        if(pL != null && pL > scoreInt) {
            limitProvince = true;
        }

        log.info(rankOne);
        List<SchoolScore> schoolScores = schoolScoreMapper.queryListByPramas(schoolScore);
        List<SchoolScore> res = new ArrayList<>();
        int cy = Calendar.getInstance().get(Calendar.YEAR);
        for (SchoolScore score : schoolScores){
            if(cy - Integer.parseInt(score.getScoreYear()) > 2) {
                continue;
            }
            if((classification.charAt(0) + "").equals("物")){
                if(score.getLotType().equals("理科") || score.getLotType().equals("物理类") || score.getLotType().equals("综合")) {
                    score.setRate(this.calaRate(score.getLowestOrder(), Integer.parseInt(rankOne)));
                    if(limitProvince && (provincet.equals("山西") || provincet.equals("江苏"))) {
                        score.setRate(0);
                    }
                    res.add(score);
                }
            } else {
                if(score.getLotType().equals("历史类") || score.getLotType().equals("文科") || score.getLotType().equals("综合")) {
                    score.setRate(this.calaRate(score.getLowestOrder(), Integer.parseInt(rankOne)));
                    if(limitProvince && (provincet.equals("山西") || provincet.equals("江苏"))) {
                        score.setRate(0);
                    }
                    res.add(score);
                }
            }
        }
        return res;
    }

    @Override
    public Map<String, List<EnrollmentPlan>> selectPrefeesionBySchoolId(Map map) throws Exception {
        EnrollmentPlan enrollmentPlan = new EnrollmentPlan();
        enrollmentPlan.setSchoolId(Long.parseLong(String.valueOf(map.get("school_id"))));
        enrollmentPlan.setProvinceName((String) map.get("province"));
        List<EnrollmentPlan> enrollmentPlanInfoBySchoolIdAndprovince = enrollmentPlanMapper.getEnrollmentPlanInfoBySchoolIdAndprovince(Integer.valueOf(String.valueOf(enrollmentPlan.getSchoolId())), enrollmentPlan.getProvinceName());
        Map<String, List<EnrollmentPlan>> filter = new HashMap<>();
        int cy = Calendar.getInstance().get(Calendar.YEAR);
        for (EnrollmentPlan plan : enrollmentPlanInfoBySchoolIdAndprovince) {
            if(cy - Integer.parseInt(plan.getStudentYear()) > 2) {
                continue;
            }
            if((((String) map.get("course_selection")).charAt(0) + "").equals("物")) {
                if(plan.getSpecialityClassification().equals("理科") || plan.getSpecialityClassification().equals("物理类") || plan.getSpecialityClassification().equals("综合")) {
                    List<EnrollmentPlan> enrollmentPlans = filter.get(plan.getStudentYear());
                    if(enrollmentPlans == null) {
                        enrollmentPlans = new ArrayList<>();
                        filter.put(plan.getStudentYear(), enrollmentPlans);
                    }
                    enrollmentPlans.add(plan);
                }
            }else {
                if(plan.getSpecialityClassification().equals("历史类") || plan.getSpecialityClassification().equals("文科") || plan.getSpecialityClassification().equals("综合")) {
                    List<EnrollmentPlan> enrollmentPlans = filter.get(plan.getStudentYear());
                    if(enrollmentPlans == null) {
                        enrollmentPlans = new ArrayList<>();
                        filter.put(plan.getStudentYear(), enrollmentPlans);
                    }
                    enrollmentPlans.add(plan);
                }
            }
        }
        return filter;
    }



    // 将 Document 对象转换为 MyObject 对象
    private SchoolScore convertToSchoolScore(Document doc) {


        Integer id= doc.getInteger("id");
        Integer schoolId= doc.getInteger("school_id");
        String schoolName= doc.getString("school_name");
        String averageScore=doc.getString("average_score");
        Integer lowestScore= doc.getInteger("lowest_score");
        Integer lowestOrder= doc.getInteger("lowest_order");
//        Double provincialLine= Double.valueOf(doc.getString("provincial_line"));
        Double provincialLine= null;
        String province=doc.getString("province");
        Integer provinceId= doc.getInteger("province_id");
        String scoreYear=doc.getString("score_year");
        String checkNeed=doc.getString("check_need");
        String admissionBatch=doc.getString("admission_batch");
        String lotType=doc.getString("lot_type");
        String school_lot_type=doc.getString("school_lot_type");
        String professional_group=doc.getString("professional_group");


        return new SchoolScore(id,schoolId,schoolName,averageScore,lowestScore,lowestOrder,provincialLine,province,provinceId,scoreYear,checkNeed,admissionBatch,lotType,school_lot_type,professional_group);
    }


    private ProfessionalScore convertToProfessionalScore(Document doc) {


        Long id= Long.valueOf(doc.getInteger("id"));
        Long schoolId= Long.valueOf(doc.getInteger("school_id"));
        String schoolName= doc.getString("school_name");
        String professionalName=doc.getString("professional_name");
        String admissionBatch=doc.getString("admission_batch");
        String averageScore=doc.getString("average_score");
        String lowestScore=doc.getString("lowest_score");
        Integer lowestOrder=doc.getInteger("lowest_order");
        String specialityClassification=doc.getString("speciality_classification");
        String provinceName=doc.getString("province_name");
        Integer enrollmentYear= doc.getInteger("enrollment_year");
        String school_lot_type=doc.getString("school_lot_type");
        String professional_group=doc.getString("professional_group");
        String professional_request=doc.getString("professional_request");


        return new ProfessionalScore(id,schoolName,schoolId,professionalName,admissionBatch,averageScore,lowestScore,lowestOrder,specialityClassification,enrollmentYear,provinceName,school_lot_type,professional_group,professional_request);
    }



}


